package org.hfy.collections;

import org.hfy.collections.helper.ItemSet;
import org.hfy.collections.helper.SymbolString;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * @Description:
 * @Author: Takagi
 * @date: 2023/5/13
 */
public class LalrAutomaton extends StdLRAutomaton {
    /*
     * @Author Takagi
     * @Description: 求解 LALR 项目集规范族
     * @date: 2023/5/13
     * @param
     * @return * @return List<ItemSet>
     **/
    @Override
    public List<ItemSet> solveItemSetFamily() {
        List<ItemSet> itemSetFamily = super.solveItemSetFamily();
        List<ItemSet> lalrItemSetFamily = new LinkedList<>();
        Set<Integer> visited = new HashSet<>();
        for (int i = 0; i < itemSetFamily.size(); i++) {
            if (visited.contains(i)) continue;

            ItemSet itemSet = itemSetFamily.get(i);
            SymbolString concentricString = new SymbolString();
            for (int j = i + 1; j < itemSetFamily.size(); j++) {
                ItemSet other = itemSetFamily.get(j);
                if (itemSet.getAllItemIgnoreLRFlag().equals(other.getAllItemIgnoreLRFlag())) {
                    concentricString.extendSymbols(getSearchSymbols(other.getFirstCoreItem().right));
                    visited.add(i);
                    visited.add(j);
                }
            }
            if (concentricString.size() > 0) {
                itemSet.addSymbolAtItemLast(concentricString);
            }
            lalrItemSetFamily.add(itemSet);
        }
        return lalrItemSetFamily;
    }
}
